Solving Missing Font Issues in .NET Docker Containers
TLDR
- Official .NET Docker images (such as Debian) are slim versions that do not include font packages by default, resulting in the absence of the
/usr/share/fontsdirectory inside the container. - The solution is to install the
ttf-mscorefonts-installerandfontconfigpackages in the Dockerfile and runfc-cacheto refresh the font cache. - The repository configuration file paths differ between Debian 11 (.NET 6) and Debian 12 (.NET 8), requiring adjustments to the
sedcommand based on the version. - Debian 11 uses
/etc/apt/sources.list; Debian 12 uses/etc/apt/sources.list.d/debian.sources.
Font Issues in Docker Containers
When you encounter this issue: If your application requires graphical rendering, PDF generation, or document processing, and the base image is a slim Linux image like mcr.microsoft.com/dotnet/aspnet, you will find that the system lacks font support.
In Linux systems, fonts are typically stored in /usr/share/fonts. Because official .NET images are minimized to reduce size, they do not come pre-installed with common font packages, which may cause this directory to be missing or empty.
Solution for .NET 6 (Debian 11)
In a Debian 11 environment, you need to modify /etc/apt/sources.list to enable the contrib repository and install the necessary packages:
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
# Enable the contrib repository
RUN sed -i'.bak' 's/$/ contrib/' /etc/apt/sources.list
# Install font installer and fontconfig
RUN apt-get update; apt-get install -y ttf-mscorefonts-installer fontconfig
# Force refresh the font cache
RUN fc-cache -f -vHandling Issues with .NET 8 Dockerfiles
When you encounter this issue: When upgrading to .NET 8 images (based on Debian 12), using the old sed command directly will fail with an exit code: 21 error.
The reason is that Debian 12 has removed /etc/apt/sources.list and switched to /etc/apt/sources.list.d/debian.sources for package management.
Solution for .NET 8 (Debian 12)
For the Debian 12 structure, you need to adjust the target file and matching rules for sed:
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
# Enable contrib in debian.sources
RUN sed -i 's/^Components: main$/& contrib/' /etc/apt/sources.list.d/debian.sources
# Install font installer and fontconfig
RUN apt-get update; apt-get install -y ttf-mscorefonts-installer fontconfig
# Force refresh the font cache
RUN fc-cache -f -vTIP
After installation, you can verify that the fonts have been successfully installed by checking if the /usr/share/fonts/truetype directory exists.
Change Log
- 2024-08-09 Initial version created.
